#include "scale_device.h"
#include "stdio.h"

#define GET_SCALE_DOUT_PIN(x) ((x)->pin[0])
#define GET_SCALE_SCK_PIN(x)  ((x)->pin[1])

static e_device_err cc_scale_read_cb(void* user_data, const char* msg, int type, void* data)
{
  cc_log_d("cc_scale_read_cb\r\n");
  user_device_t dev = (user_device_t)user_data;
  HX711* scale = (HX711*)dev->hard_drv;
  if (!scale)
  {
    cc_log_e("hard drc is null\r\n");
    return DEVICE_EHARD_DRV_NULL;
  }
  // TODO 这两个度量到时候自己测
  if (type == CC_SCALE_READ_GRAM)
  {
    scale->set_scale(425.f);
  }
  if (type == CC_SCALE_READ_KG)
  {
    // scale->set_scale(2280.f);
  }
  dev->num_data[0] = scale->get_units(5);
  if (data != CC_NULL)
  {
    float* weight = (float*)data;
    *weight = dev->num_data[0];
    cc_log_d("cc_scale_read:%.4f\r\n", *weight);
  }

  return DEVICE_EOK;
}
static e_device_err cc_scale_write_cb(void* user_data, const char* msg, int type, void* data)
{
  cc_log_d("cc_scale_write_cb\r\n");
  return DEVICE_EOK;
}
static e_device_err cc_scale_control_cb(void* user_data, const char* msg, int type, void* data)
{
  cc_log_d("cc_scale_control_cb\r\n");
  user_device_t dev = (user_device_t)user_data;
  HX711* scale = (HX711*)dev->hard_drv;
  if (!scale)
  {
    cc_log_e("hard drc is null\r\n");
    return DEVICE_EHARD_DRV_NULL;
  }
  if (type == CC_SCALE_RESET)
  {
    scale->tare();    // 说白了 去皮
  }
  cc_log("cc_scale_control_cb success!!!\r\n");
  return DEVICE_EOK;
}

e_device_err cc_scale_init(void* device)
{
  user_device_t dev = (user_device_t)device;
  dev->hard_drv = new HX711();
  HX711* scale = (HX711*)dev->hard_drv;
  scale->begin(GET_SCALE_DOUT_PIN(dev), GET_SCALE_SCK_PIN(dev));
  // // 这个需要自己测算 详情参考这个库的readme
  // //  used to return weight in grams, kg, ounces, whatever
  // 其实就是把adc采样除以这个值 就是你要的计数单位
  scale->set_scale(425.f);
  scale->tare();    // 清零计数值
  dev->control_cb = cc_scale_control_cb;
  dev->read_cb = cc_scale_read_cb;
  dev->write_cb = cc_scale_write_cb;
  return DEVICE_EOK;
}
CC_DEVICE_INIT_MOUNT(cc_scale_init, CC_DEVICE_TYPE_SCALE)
